package com.cat.chapter036;

/**
 * @author cat
 * @description https://leetcode.cn/problems/serialize-and-deserialize-binary-tree/
 * @create 2025/6/16 18:11
 * @since JDK17
 */

public class Codec {
    StringBuilder s = new StringBuilder();
    int cnt;
    // Encodes a tree to a single string.
    // 序列化
    public String serialize(TreeNode root) {
        s = new StringBuilder();
        f(root, s);
        System.out.println(s.toString());
        return s.toString();
    }
    public void f(TreeNode root, StringBuilder s) {
        if (root == null) {
            s.append("#,");
        } else {
            s.append(root.val + ",");
            f(root.left, s);
            f(root.right, s);
        }
    }

    // Decodes your encoded data to tree.
    // 反序列化
    public TreeNode deserialize(String data) {
        String[] strings = data.toString().split(",");
        cnt = 0;
        return g(strings);
    }

    public TreeNode g(String[] strings) {
        String cur = strings[cnt++];
        if ("#".equals(cur)) {
            return null;
        } else {
            TreeNode node = new TreeNode(Integer.valueOf(cur));
            node.left = g(strings);
            node.right = g(strings);
            return node;
        }
    }
}

